using MediatR;
using Process.Api.Application.Command.BOM;
using Process.BLL;
using Process.DAL;
using Process.ErrorCod;
using Process.Model;

namespace Process.Api.Application.Handler.BOM
{
    public class DeleteBomHandler : IRequestHandler<DeleteBomCommand, ApiResult<int>>
    {
        private readonly IProcessRepository<BomTable> bomRepo;

        public DeleteBomHandler(IProcessRepository<BomTable> bomRepo)
        {
            this.bomRepo = bomRepo;
        }

        /// <summary>
        /// 删除BOM数据（软删除）
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> Handle(DeleteBomCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>();

            try
            {
                // 查找要删除的BOM
                var bom = bomRepo.GetAllAsync().FirstOrDefault(x => x.Id == request.Id && !x.IsDelete);
                if (bom == null)
                {
                    result.Code = ErrorStatus.Error;
                    result.Message = "BOM不存在或已被删除";
                    result.Data = 0;
                    return result;
                }

                // 执行软删除
                bom.IsDelete = true;
                bom.UpdateTime = DateTime.Now;
                // 可以设置删除人，如果有用户信息的话
                // bom.Updater = currentUser;

                var res = await bomRepo.UpdateAsync(bom);
                if (res > 0)
                {
                    result.Code = ErrorStatus.Success;
                    result.Message = "删除BOM成功";
                    result.Data = res;
                }
                else
                {
                    result.Code = ErrorStatus.Error;
                    result.Message = "删除BOM失败";
                    result.Data = 0;
                }
            }
            catch (Exception ex)
            {
                result.Code = ErrorStatus.Error;
                result.Message = $"删除BOM时发生错误: {ex.Message}";
                result.Data = 0;
            }

            return result;
        }
    }
}




